<?php

namespace Biz\model;

use Doraemon\pockets\datebase\BaseDbModel;
use Biz\tools\ShopArea;

class ShopInvoiceInformation extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop_info';

    const _DATABASE_ = 'shop_info';

    const _TABLE_NAME = 'shop_invoice_information';

    const _SUB_TABLE = false;


    const TYPE_PERSONAL = 1;//发票类型：个人
    const TYPE_GENERAL = 2;//发票类型：一般纳税人
    const TYPE_SMALL = 3;//发票类型：小规模纳税人

    public static $typeDesc = [
        self::TYPE_PERSONAL => '个人',
        self::TYPE_GENERAL => '一般纳税人',
        self::TYPE_SMALL => '小规模纳税人',
    ];

    public static function addData($data)
    {
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function updateData($data, $where)
    {
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function hasInvoiceInfo($shopId)
    {
        return self::has(['shop_id' => $shopId]);
    }

    public static function getInvoiceInfo($shopId, $areaToArray = true)
    {
        $info = self::get('*', ['shop_id' => $shopId]);
        self::_formatInfo($info, $areaToArray);
        return $info;
    }


    public static function getInvoiceInfoList($shopIds)
    {
        $list = self::select("*", ['shop_id' => $shopIds]);
        $formatData = [];
        foreach ($list as $info) {
            self::_formatInfo($info, false);

            $formatData[$info["shop_id"]] = $info;
        }
        return $formatData;
    }


    private static function _formatInfo(&$info, $areaToArray = true)
    {
        if (empty($info))
            return;

        foreach ($info as $key => $value) {
            switch ($key) {
                case 'send_address_code':
                    if ($areaToArray) {
                        if (explode(',', $value) !== false) {
                            $info[$key] = explode(',', $value);
                        } else {
                            $info[$key] = [];
                        }
                    }
                    $info['send_address_str'] = $value ? ShopArea::locationId2String($value) : '';
                    break;
                case 'type':
                    if ($info['type'] == self::TYPE_PERSONAL) {
                        $info['type_desc'] = '个人';
                    } else if ($info['type'] == self::TYPE_GENERAL) {
                        $info['type_desc'] = '一般纳税人';
                    } else if ($info['type'] == self::TYPE_SMALL) {
                        $info['type_desc'] = '小规模纳税人';
                    }
                    break;
            }
        }
    }
}